package com.xjc.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjc.business.entity.domain.*;
import com.xjc.business.entity.po.buildadmin.BuildAdminLogoPo;
import com.xjc.business.entity.po.schadmin.PersonPo;
import com.xjc.business.entity.vo.PageVo;
import com.xjc.business.entity.vo.buildadmin.BuildAdminLoginVo;
import com.xjc.business.entity.vo.classadmin.ClassAdminLoginVo;
import com.xjc.business.entity.vo.schadmin.BuildingRestAdminVo;
import com.xjc.business.entity.vo.schadmin.CollegeRestAdminVo;
import com.xjc.business.entity.vo.schadmin.PersonVo;
import com.xjc.business.service.BuildingAdminRelationsService;
import com.xjc.business.service.BuildingAdminsService;
import com.xjc.business.mapper.BuildingAdminsMapper;
import com.xjc.business.service.SchoolBuildingAdminRelationsService;
import com.xjc.business.service.SchoolSetsService;
import com.xjc.system.constants.MyConstants;
import com.xjc.system.exception.MyException;
import com.xjc.system.result.Result;
import com.xjc.system.result.ResultCode;
import com.xjc.system.utils.BcryptUtil;
import com.xjc.system.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author root
* @description 针对表【building_admins(宿舍管理员)】的数据库操作Service实现
* @createDate 2025-01-25 10:24:31
*/
@Service
public class BuildingAdminsServiceImpl extends ServiceImpl<BuildingAdminsMapper, BuildingAdmins>
    implements BuildingAdminsService {

    @Autowired
    @Lazy
    SchoolBuildingAdminRelationsService schoolBuildingAdminRelationsService;

    @Autowired
    @Lazy
    BuildingAdminRelationsService buildingAdminRelationsService;

    @Autowired
    @Lazy
    SchoolSetsService schoolSetsService;

    /**
     * 分页查询人员信息
     *
     * @param pageSize      每页显示条数
     * @param currentPage   当前页码
     * @param adminUserName 用户名
     * @param adminNickName 昵称
     * @param schoolId
     * @return 信息
     */
    @Override
    public Result<PageVo<PersonVo>> getBuildingAdminPage(Integer pageSize, Integer currentPage, String adminUserName, String adminNickName, Integer schoolId) {

        LambdaQueryWrapper<SchoolBuildingAdminRelations> schoolBuildingAdminRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        schoolBuildingAdminRelationsLambdaQueryWrapper.eq(SchoolBuildingAdminRelations::getSchId,schoolId);
        List<SchoolBuildingAdminRelations> schoolBuildingAdminRelationsList = schoolBuildingAdminRelationsService.list(schoolBuildingAdminRelationsLambdaQueryWrapper);
        List<Integer> collectIdList = schoolBuildingAdminRelationsList.stream().map(SchoolBuildingAdminRelations::getBuildAdminId).collect(Collectors.toList());
        PageVo<PersonVo> pageVo = new PageVo<>();

        if (collectIdList.isEmpty()){
            return Result.okWithData(pageVo);
        }


        LambdaQueryWrapper<BuildingAdmins> buildingAdminsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        buildingAdminsLambdaQueryWrapper.like(!adminUserName.isEmpty(),BuildingAdmins::getUsername,adminUserName);
        buildingAdminsLambdaQueryWrapper.like(!adminNickName.isEmpty(),BuildingAdmins::getNickname,adminNickName);

        Page<BuildingAdmins> buildingAdminsPage = new Page<>(currentPage, pageSize);
        page(buildingAdminsPage,buildingAdminsLambdaQueryWrapper);
        List<BuildingAdmins> buildingAdminsPageRecords = buildingAdminsPage.getRecords();
        List<PersonVo> personVoList = buildingAdminsPageRecords.stream().map(buildingAdmins -> {
            PersonVo personVo = new PersonVo();
            personVo.setId(buildingAdmins.getId());
            personVo.setUsername(buildingAdmins.getUsername());
            personVo.setNickname(buildingAdmins.getNickname());
            personVo.setPic(buildingAdmins.getPic());
            personVo.setPhone(buildingAdmins.getPhone());
            personVo.setEmail(buildingAdmins.getEmail());
            personVo.setStatus(MyConstants.USER_STATUS.get(buildingAdmins.getStatus()));
            personVo.setCreateTime(buildingAdmins.getCreateTime());
            personVo.setType(1);
            return personVo;
        }).collect(Collectors.toList());

        pageVo.setCurrent(currentPage);
        pageVo.setData(personVoList);
        pageVo.setPageCount(buildingAdminsPage.getPages());
        pageVo.setSize(pageSize);
        pageVo.setTotal(buildingAdminsPage.getTotal());

        return Result.okWithData(pageVo);
    }

    /**
     * 添加管理员
     *
     * @param personPo 管理员信息
     * @return 反馈
     */
    @Transactional
    @Override
    public Result<String> addBuildingAdmin(PersonPo personPo) {
        BuildingAdmins buildingAdmins = new BuildingAdmins();
        buildingAdmins.setUsername(personPo.getUsername());
        buildingAdmins.setPassword(BcryptUtil.hashPassword(personPo.getPassword()));
        buildingAdmins.setNickname(personPo.getNickname());
        buildingAdmins.setPhone(personPo.getPhone());
        buildingAdmins.setEmail(personPo.getEmail());
        buildingAdmins.setPic(personPo.getPic());
        buildingAdmins.setStatus(1);
        buildingAdmins.setUpdateTime(new Date());
        buildingAdmins.setCreateTime(new Date());

        save(buildingAdmins);

        SchoolBuildingAdminRelations schoolBuildingAdminRelations = new SchoolBuildingAdminRelations();
        schoolBuildingAdminRelations.setSchId(personPo.getSchoolId());
        schoolBuildingAdminRelations.setBuildAdminId(buildingAdmins.getId());
        schoolBuildingAdminRelationsService.save(schoolBuildingAdminRelations);

        return Result.okWithData("增加成功");
    }

    /**
     * 获取学校中空闲的楼宇管理员列表
     * @param schoolId 学校id
     * @return 信息
     */
    @Override
    public Result<List<BuildingRestAdminVo>> getRestBuildingAdminList(Integer schoolId) {
        LambdaQueryWrapper<SchoolBuildingAdminRelations> schoolBuildingAdminRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        schoolBuildingAdminRelationsLambdaQueryWrapper.eq(SchoolBuildingAdminRelations::getSchId, schoolId);
        List<SchoolBuildingAdminRelations> schoolCollageAdminRelationsList = schoolBuildingAdminRelationsService.list(schoolBuildingAdminRelationsLambdaQueryWrapper);

        List<BuildingRestAdminVo> BuildingRestAdminVo = new ArrayList<>();
        if(!schoolCollageAdminRelationsList.isEmpty()){

            List<Integer> collectIdList = schoolCollageAdminRelationsList.stream().map(SchoolBuildingAdminRelations::getBuildAdminId).collect(Collectors.toList());
            List<Integer> collectNotIdList = buildingAdminRelationsService.list().stream().map(BuildingAdminRelations::getBuildAdminId).collect(Collectors.toList());

            LambdaQueryWrapper<BuildingAdmins> buildingAdminsLambdaQueryWrapper = new LambdaQueryWrapper<>();
            buildingAdminsLambdaQueryWrapper.in(BuildingAdmins::getId, collectIdList); //指定学校
            buildingAdminsLambdaQueryWrapper.notIn(!collectNotIdList.isEmpty(),BuildingAdmins::getId,collectNotIdList); //未管理楼宇

            List<BuildingAdmins> buildingAdminsList = list(buildingAdminsLambdaQueryWrapper);

            BuildingRestAdminVo = buildingAdminsList.stream().map(buildingAdmins -> {
                BuildingRestAdminVo buildingRestAdminVo = new BuildingRestAdminVo();
                buildingRestAdminVo.setId(buildingAdmins.getId());
                buildingRestAdminVo.setUsername(buildingAdmins.getUsername());
                buildingRestAdminVo.setNickname(buildingAdmins.getNickname());
                return buildingRestAdminVo;
            }).collect(Collectors.toList());
        }

        return Result.okWithData(BuildingRestAdminVo);
    }

    /**
     * 登录
     * @param buildAdminLogoPo 登录参数
     * @return 登录成功返回token，失败返回错误信息
     */
    @Override
    public Result<BuildAdminLoginVo> doLogin(BuildAdminLogoPo buildAdminLogoPo) {
        String password = buildAdminLogoPo.getPassword();
        String username = buildAdminLogoPo.getUsername();

        LambdaQueryWrapper<BuildingAdmins> buildingAdminsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        buildingAdminsLambdaQueryWrapper.eq(BuildingAdmins::getUsername, username);
        BuildingAdmins buildingAdminsFromDB = getOne(buildingAdminsLambdaQueryWrapper);

        if (buildingAdminsFromDB == null) {
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.USERNAME_ERROR);
        }

        if (!(BcryptUtil.checkPassword(password,buildingAdminsFromDB.getPassword()))){
            throw new MyException(ResultCode.SUCCESS.getCode(), MyConstants.PASSWORD_ERROR);
        }

        if (!schoolSetsService.sureHasSet(MyConstants.BUILD_ROLE,buildingAdminsFromDB.getId())) {
            throw new MyException(ResultCode.SUCCESS.getCode(),ResultCode.NOTOPEANSET.getMessage());
        }

        BuildAdminLoginVo buildAdminLoginVo = new BuildAdminLoginVo();
        buildAdminLoginVo.setId(buildingAdminsFromDB.getId());
        buildAdminLoginVo.setUsername(buildingAdminsFromDB.getUsername());
        buildAdminLoginVo.setNickname(buildingAdminsFromDB.getNickname());
        buildAdminLoginVo.setPic(buildingAdminsFromDB.getPic());
        buildAdminLoginVo.setToken(TokenUtils.generateToken(buildingAdminsFromDB.getId()));

        LambdaQueryWrapper<BuildingAdminRelations> buildingAdminRelationsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        buildingAdminRelationsLambdaQueryWrapper.eq(BuildingAdminRelations::getBuildAdminId,buildingAdminsFromDB.getId());

        BuildingAdminRelations buildingAdminRelations = buildingAdminRelationsService.getOne(buildingAdminRelationsLambdaQueryWrapper);

        if(buildingAdminRelations !=null){
            buildAdminLoginVo.setBuildingId(buildingAdminRelations.getBuildId());
        }

        return Result.okWithData(buildAdminLoginVo);
    }
}




